package com.gitee.apiconf.common;

import com.gitee.easyopen.config.ConfigMsg;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ChannelContext {
    // key:app
    private static Map<String, ChannelGroup> appChannelGroup = new ConcurrentHashMap<>(8);

    public synchronized static Set<String> listAppNames() {
        return appChannelGroup.keySet();
    }

    public synchronized static void writeAndFlush(ConfigMsg msg) {
        ChannelGroup channelGroup = ChannelContext.getChannelGroupByApp(msg.getApp());
        if (channelGroup != null) {
            channelGroup.writeAndFlush(msg);
        }
    }

    public synchronized static void removeChannel(Channel channel) {
        Collection<ChannelGroup> channelGroups = appChannelGroup.values();
        for (ChannelGroup channelGroup : channelGroups) {
            Channel ch = channelGroup.find(channel.id());
            if (ch != null) {
                channelGroup.remove(ch);
                break;
            }
        }
    }

    public synchronized static ChannelGroup getChannelGroupByApp(String app) {
        return appChannelGroup.get(app);
    }

    public synchronized static void saveChannel(String app, Channel ch) {
        ChannelGroup channelGroup = appChannelGroup.get(app);
        if (channelGroup == null) {
            channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            appChannelGroup.put(app, channelGroup);
        }
        channelGroup.add(ch);
    }
}
